<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container {
            display: flex;
        }

        .container div {
            padding: 5px 10px;
            margin: 0 5px;
            cursor: pointer;
        }

        .active {
            background-color: chocolate;
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="container" id="container"></div>

    <script>
        // 1. 定义一个保存所有分类的数组
        const types = [
            { name: '全部' },
            { name: '历史' },
            { name: '战争' },
            { name: '古装' },
        ]
        // 2. 定义一个数据，用来表示当前选中的分类
        let currentIndex = 2;

        typesRender();

        function typesRender() {
            container.innerHTML = types.map((item, index) => {
                if (index == currentIndex) {
                    return `<div class="active" i="${index}">${item.name}</div>`
                }
                return `<div i="${index}">${item.name}</div>`
            }).join('')
        }

        container.onclick = function (event) {
            if (event.target.className !== 'container') {
                // event.target获取当前点击的标签
                // event.target.getAttribute("i") 获取当前点击的标签对应的下标
                currentIndex = event.target.getAttribute("i");
                typesRender();
            }
        }


    </script>
</body>

</html>